package com.zlm.pc;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author: 郑
 * 多线程顺序执行
 */
public class PcDemo3 {
    public static void main(String[] args) {
        Data3 data3 = new Data3();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data3.prinA();
            }
        },"A").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data3.prinB();
            }
        },"B").start();
        new Thread(()-> {
            for (int i = 0; i < 10; i++) {
                data3.prinC();
            }
        },"C").start();
    }
}

class Data3{
    private int num=0;
    private final Lock lock =  new ReentrantLock();
    Condition condition1 = lock.newCondition();
    Condition condition2 = lock.newCondition();
    Condition condition3 = lock.newCondition();

    public void prinA(){
        lock.lock();

        try {
            while (num !=0){
                //等待
                condition1.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"=>AAAAAAAAAAA");
            //通知
            condition2.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void prinB(){
        lock.lock();

        try {
            while (num !=1){
                //等待
                condition2.await();
            }
            num++;
            System.out.println(Thread.currentThread().getName()+"=>BBBBBBBBB");
            //通知
            condition3.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
    public void prinC(){
        lock.lock();

        try {
            while (num !=2){
                //等待
                condition3.await();
            }
            num=0;
            System.out.println(Thread.currentThread().getName()+"=>CCCCCCCCCC");
            //通知
            condition1.signal();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //解锁
            lock.unlock();
        }

    }
}
